package org.hong.monkey.rpc.netty

import java.io.File

import org.hong.monkey.{HttpFileServer, MonkeyConf}
import org.hong.monkey.rpc.RpcEnvFileServer

private[netty] class HttpBasedFileServer(conf: MonkeyConf)
  extends RpcEnvFileServer {

  @volatile private var httpFileServer: HttpFileServer = _

  override def addFile(file: File): String = {
    getFileServer().addFile(file)
  }

  override def addJar(file: File): String = {
    getFileServer().addJar(file)
  }

  def shutdown(): Unit = {
    if (httpFileServer != null) {
      httpFileServer.stop()
    }
  }

  private def getFileServer(): HttpFileServer = {
    if (httpFileServer == null) synchronized {
      if (httpFileServer == null) {
        httpFileServer = startFileServer()
      }
    }
    httpFileServer
  }

  private def startFileServer(): HttpFileServer = {
    val fileServerPort = conf.getInt("monkey.fileserver.port", 0)
    val server = new HttpFileServer(conf, fileServerPort)
    server.initialize()
    server
  }

}
